/**
 * 系统监控页面
 * 
 * 功能特性：
 * - 系统状态实时监控
 * - 健康检查结果展示
 * - 日志查看和管理
 * - 性能指标图表
 * - 告警信息展示
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

// React核心库导入
import React, { useState, useEffect } from 'react';
// React Router路由相关导入
import { useNavigate } from 'react-router-dom';
// Ant Design组件库导入
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Tag,
  Button,
  Space,
  Typography,
  Progress,
  Timeline,
  Alert,
  Modal,
  Form,
  Select,
  DatePicker,
  message,
  Tabs,
  Descriptions,
  Badge,
  Tooltip
} from 'antd';
// Ant Design图标库导入
import {
  DashboardOutlined,
  HeartOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ReloadOutlined,
  SettingOutlined,
  DeleteOutlined,
  EyeOutlined,
  FileTextOutlined,
  BarChartOutlined,
  LineChartOutlined
} from '@ant-design/icons';
// 日期处理库导入
import dayjs from 'dayjs';
// 相对时间插件导入
import relativeTime from 'dayjs/plugin/relativeTime';

// 启用相对时间插件
dayjs.extend(relativeTime);

// 解构Ant Design组件
const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

// 监控数据接口
interface SystemStatus {
  uptime: string;
  cpuUsage: number;
  memoryUsed: number;
  memoryTotal: number;
  diskUsed: number;
  diskTotal: number;
  activeConnections: number;
  requestsPerSecond: number;
  errorRate: number;
  lastChecked: string;
}

// 健康检查结果接口
interface HealthCheckResult {
  name: string;
  isHealthy: boolean;
  message: string;
  duration: string;
  data: Record<string, any>;
}

// 日志条目接口
interface LogEntry {
  id: string;
  timestamp: string;
  level: string;
  message: string;
  details: string;
  exception: string;
  userId: string;
  userName: string;
  clientIp: string;
  requestPath: string;
  requestMethod: string;
  statusCode: number;
  executionTimeMs: number;
  category: string;
  tags: Record<string, string>;
}

// 性能指标接口
interface PerformanceMetric {
  name: string;
  value: number;
  unit: string;
  timestamp: string;
  tags: Record<string, string>;
}

// 日志级别选项
const logLevelOptions = [
  { label: '调试', value: 'Debug' },
  { label: '信息', value: 'Information' },
  { label: '警告', value: 'Warning' },
  { label: '错误', value: 'Error' },
  { label: '严重', value: 'Critical' }
];

// 日志级别颜色映射
const logLevelColors = {
  Debug: 'default',
  Information: 'blue',
  Warning: 'orange',
  Error: 'red',
  Critical: 'purple'
};

/**
 * 系统监控页面组件
 */
const SystemMonitor: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [systemStatus, setSystemStatus] = useState<SystemStatus | null>(null);
  const [healthChecks, setHealthChecks] = useState<HealthCheckResult[]>([]);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [metrics, setMetrics] = useState<PerformanceMetric[]>([]);
  const [selectedLog, setSelectedLog] = useState<LogEntry | null>(null);
  const [logModalVisible, setLogModalVisible] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(30); // 秒

  // 表单状态
  const [logLevel, setLogLevel] = useState<string>('Information');
  const [logCount, setLogCount] = useState<number>(100);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(1, 'hour'),
    dayjs()
  ]);

  // 路由导航
  const navigate = useNavigate();

  // 加载系统状态
  const loadSystemStatus = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const mockStatus: SystemStatus = {
        uptime: '2天 14小时 32分钟',
        cpuUsage: 23.5,
        memoryUsed: 5.2 * 1024 * 1024 * 1024,
        memoryTotal: 8 * 1024 * 1024 * 1024,
        diskUsed: 128 * 1024 * 1024 * 1024,
        diskTotal: 500 * 1024 * 1024 * 1024,
        activeConnections: 156,
        requestsPerSecond: 12.8,
        errorRate: 0.8,
        lastChecked: new Date().toISOString()
      };

      setSystemStatus(mockStatus);
    } catch (error) {
      message.error('加载系统状态失败');
    }
  };

  // 加载健康检查结果
  const loadHealthChecks = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800));
      
      const mockHealthChecks: HealthCheckResult[] = [
        {
          name: 'Database',
          isHealthy: true,
          message: '数据库连接正常',
          duration: '15ms',
          data: {
            connectionTime: 15,
            database: 'SQL Server',
            version: '2019'
          }
        },
        {
          name: 'MCP Servers',
          isHealthy: true,
          message: 'MCP服务器运行正常',
          duration: '23ms',
          data: {
            connectedServers: 6,
            totalServers: 8,
            activeTools: 45
          }
        },
        {
          name: 'Memory',
          isHealthy: true,
          message: '内存使用正常',
          duration: '5ms',
          data: {
            usagePercent: 65.2,
            availableMB: 2832,
            totalMB: 8192
          }
        },
        {
          name: 'Disk',
          isHealthy: true,
          message: '磁盘空间充足',
          duration: '8ms',
          data: {
            usagePercent: 25.6,
            freeGB: 372,
            totalGB: 500
          }
        }
      ];

      setHealthChecks(mockHealthChecks);
    } catch (error) {
      message.error('加载健康检查结果失败');
    }
  };

  // 加载日志
  const loadLogs = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 600));
      
      const mockLogs: LogEntry[] = [
        {
          id: '1',
          timestamp: new Date().toISOString(),
          level: 'Information',
          message: '用户登录成功',
          details: '用户 admin 登录系统',
          exception: '',
          userId: 'admin',
          userName: 'admin',
          clientIp: '192.168.1.100',
          requestPath: '/api/account/login',
          requestMethod: 'POST',
          statusCode: 200,
          executionTimeMs: 125,
          category: 'Authentication',
          tags: {}
        },
        {
          id: '2',
          timestamp: new Date(Date.now() - 1000 * 60).toISOString(),
          level: 'Warning',
          message: 'MCP服务器连接超时',
          details: '服务器 mcp-server-01 连接超时',
          exception: 'TimeoutException',
          userId: 'system',
          userName: 'system',
          clientIp: '127.0.0.1',
          requestPath: '/api/mcp-servers/1/connect',
          requestMethod: 'POST',
          statusCode: 500,
          executionTimeMs: 5000,
          category: 'MCP',
          tags: {}
        },
        {
          id: '3',
          timestamp: new Date(Date.now() - 1000 * 120).toISOString(),
          level: 'Error',
          message: '数据库查询失败',
          details: '查询用户信息时发生错误',
          exception: 'SqlException: Connection timeout',
          userId: 'system',
          userName: 'system',
          clientIp: '127.0.0.1',
          requestPath: '/api/users/1',
          requestMethod: 'GET',
          statusCode: 500,
          executionTimeMs: 3000,
          category: 'Database',
          tags: {}
        }
      ];

      setLogs(mockLogs);
    } catch (error) {
      message.error('加载日志失败');
    }
  };

  // 刷新所有数据
  const refreshAllData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadSystemStatus(),
        loadHealthChecks(),
        loadLogs()
      ]);
    } finally {
      setLoading(false);
    }
  };

  // 查看日志详情
  const viewLogDetails = (log: LogEntry) => {
    setSelectedLog(log);
    setLogModalVisible(true);
  };

  // 清理旧日志
  const cleanupOldLogs = async () => {
    Modal.confirm({
      title: '确认清理',
      content: '确定要清理30天前的日志吗？',
      onOk: async () => {
        try {
          // 模拟API调用
          await new Promise(resolve => setTimeout(resolve, 500));
          message.success('日志清理完成');
          await loadLogs();
        } catch (error) {
          message.error('清理日志失败');
        }
      }
    });
  };

  // 自动刷新
  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(refreshAllData, refreshInterval * 1000);
      return () => clearInterval(interval);
    }
  }, [autoRefresh, refreshInterval]);

  // 组件挂载时加载数据
  useEffect(() => {
    refreshAllData();
  }, []);

  // 系统状态卡片
  const renderSystemStatusCards = () => {
    if (!systemStatus) return null;

    const memoryUsagePercent = (systemStatus.memoryUsed / systemStatus.memoryTotal) * 100;
    const diskUsagePercent = (systemStatus.diskUsed / systemStatus.diskTotal) * 100;

    return (
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="系统运行时间"
              value={systemStatus.uptime}
              prefix={<DashboardOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="CPU使用率"
              value={systemStatus.cpuUsage}
              suffix="%"
              precision={1}
              valueStyle={{ 
                color: systemStatus.cpuUsage > 80 ? '#cf1322' : systemStatus.cpuUsage > 60 ? '#faad14' : '#3f8600' 
              }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="内存使用率"
              value={memoryUsagePercent}
              suffix="%"
              precision={1}
              valueStyle={{ 
                color: memoryUsagePercent > 80 ? '#cf1322' : memoryUsagePercent > 60 ? '#faad14' : '#3f8600' 
              }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="活跃连接数"
              value={systemStatus.activeConnections}
              prefix={<DashboardOutlined />}
            />
          </Card>
        </Col>
      </Row>
    );
  };

  // 健康检查结果
  const renderHealthChecks = () => (
    <Card title="健康检查" extra={<Button icon={<ReloadOutlined />} onClick={loadHealthChecks}>刷新</Button>}>
      <Row gutter={[16, 16]}>
        {healthChecks.map((check, index) => (
          <Col xs={24} sm={12} lg={6} key={index}>
            <Card 
              size="small" 
              style={{ 
                borderLeft: `4px solid ${check.isHealthy ? '#52c41a' : '#ff4d4f'}`,
                marginBottom: 16
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                {check.isHealthy ? (
                  <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                ) : (
                  <CloseCircleOutlined style={{ color: '#ff4d4f', marginRight: 8 }} />
                )}
                <Text strong>{check.name}</Text>
              </div>
              <Text type="secondary">{check.message}</Text>
              <div style={{ marginTop: 8, fontSize: 12 }}>
                <Text type="secondary">耗时: {check.duration}</Text>
              </div>
            </Card>
          </Col>
        ))}
      </Row>
    </Card>
  );

  // 日志表格列定义
  const logColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a: LogEntry, b: LogEntry) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
      width: 180
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => (
        <Tag color={logLevelColors[level as keyof typeof logLevelColors]}>
          {level}
        </Tag>
      ),
      width: 100
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => <Tag color="blue">{category}</Tag>,
      width: 120
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 120
    },
    {
      title: '状态码',
      dataIndex: 'statusCode',
      key: 'statusCode',
      render: (code: number) => (
        <Tag color={code >= 200 && code < 300 ? 'green' : code >= 400 && code < 500 ? 'orange' : 'red'}>
          {code}
        </Tag>
      ),
      width: 100
    },
    {
      title: '耗时',
      dataIndex: 'executionTimeMs',
      key: 'executionTimeMs',
      render: (time: number) => `${time}ms`,
      width: 100
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: LogEntry) => (
        <Button 
          type="link" 
          icon={<EyeOutlined />}
          onClick={() => viewLogDetails(record)}
        >
          详情
        </Button>
      ),
      width: 100
    }
  ];

  return (
    <div>
      {/* 页面标题和操作区域 */}
      <div style={{ marginBottom: 24 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              <DashboardOutlined /> 系统监控
            </Title>
          </Col>
          <Col>
            <Space>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={refreshAllData}
                loading={loading}
              >
                刷新
              </Button>
              <Button 
                icon={<DeleteOutlined />}
                onClick={cleanupOldLogs}
                danger
              >
                清理日志
              </Button>
              <Button 
                icon={<SettingOutlined />}
                onClick={() => message.info('设置功能正在开发中')}
              >
                设置
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 自动刷新控制 */}
      <Card style={{ marginBottom: 24 }}>
        <Row align="middle">
          <Col span={4}>
            <Text strong>自动刷新：</Text>
          </Col>
          <Col span={6}>
            <Select
              value={autoRefresh}
              onChange={setAutoRefresh}
              style={{ width: '100%' }}
            >
              <Option value={true}>开启</Option>
              <Option value={false}>关闭</Option>
            </Select>
          </Col>
          <Col span={6} offset={1}>
            <Text strong>刷新间隔：</Text>
          </Col>
          <Col span={6}>
            <Select
              value={refreshInterval}
              onChange={setRefreshInterval}
              style={{ width: '100%' }}
              disabled={!autoRefresh}
            >
              <Option value={10}>10秒</Option>
              <Option value={30}>30秒</Option>
              <Option value={60}>1分钟</Option>
              <Option value={300}>5分钟</Option>
            </Select>
          </Col>
        </Row>
      </Card>

      <Tabs
        defaultActiveKey="status"
        items={[
          {
            key: 'status',
            label: '系统状态',
            children: (
              <>
                {renderSystemStatusCards()}
                {renderHealthChecks()}
              </>
            )
          },
          {
            key: 'logs',
            label: '日志监控',
            children: (
              <Card
                title="系统日志"
                extra={
                  <Space>
                    <Select
                      value={logLevel}
                      onChange={setLogLevel}
                      style={{ width: 120 }}
                    >
                      {logLevelOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                    <Select
                      value={logCount}
                      onChange={setLogCount}
                      style={{ width: 100 }}
                    >
                      <Option value={50}>50条</Option>
                      <Option value={100}>100条</Option>
                      <Option value={200}>200条</Option>
                      <Option value={500}>500条</Option>
                    </Select>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={loadLogs}
                    >
                      刷新
                    </Button>
                  </Space>
                }
              >
                <Table
                  columns={logColumns}
                  dataSource={logs}
                  rowKey="id"
                  pagination={{ pageSize: 10 }}
                  loading={loading}
                  size="small"
                />
              </Card>
            )
          },
          {
            key: 'metrics',
            label: '性能指标',
            children: (
              <Card title="性能指标">
                <Alert
                  message="性能指标功能正在开发中"
                  description="将包含CPU、内存、磁盘、网络等性能指标的图表展示。"
                  type="info"
                  showIcon
                />
              </Card>
            )
          }
        ]}
      />

      {/* 日志详情模态框 */}
      <Modal
        title="日志详情"
        open={logModalVisible}
        onCancel={() => setLogModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setLogModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedLog && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="日志ID">{selectedLog.id}</Descriptions.Item>
            <Descriptions.Item label="时间">{dayjs(selectedLog.timestamp).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            <Descriptions.Item label="级别">
              <Tag color={logLevelColors[selectedLog.level as keyof typeof logLevelColors]}>
                {selectedLog.level}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="消息">{selectedLog.message}</Descriptions.Item>
            <Descriptions.Item label="详情">{selectedLog.details}</Descriptions.Item>
            {selectedLog.exception && (
              <Descriptions.Item label="异常">
                <Text code>{selectedLog.exception}</Text>
              </Descriptions.Item>
            )}
            <Descriptions.Item label="分类">{selectedLog.category}</Descriptions.Item>
            <Descriptions.Item label="用户">{selectedLog.userName}</Descriptions.Item>
            <Descriptions.Item label="客户端IP">{selectedLog.clientIp}</Descriptions.Item>
            <Descriptions.Item label="请求路径">{selectedLog.requestPath}</Descriptions.Item>
            <Descriptions.Item label="请求方法">{selectedLog.requestMethod}</Descriptions.Item>
            <Descriptions.Item label="状态码">{selectedLog.statusCode}</Descriptions.Item>
            <Descriptions.Item label="执行时间">{selectedLog.executionTimeMs}ms</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default SystemMonitor;